package com.duck.inspection.config;

import com.coze.openapi.client.files.UploadFileReq;
import com.coze.openapi.client.files.model.FileInfo;
import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.connversations.CreateConversationReq;
import com.coze.openapi.client.connversations.CreateConversationResp;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.service.CozeAPI;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class CozeChatApiClient {

    private final CozeProperties cozeProperties;

    public CozeChatApiClient(CozeProperties cozeProperties) {
        this.cozeProperties = cozeProperties;
    }

    public String createConversation() {
        TokenAuth auth = new TokenAuth(cozeProperties.getPersonalToken());
        CozeAPI api = new CozeAPI.Builder()
                .baseURL(cozeProperties.getApiBase())
                .auth(auth)
                .build();
        CreateConversationResp resp = api.conversations()
                .create(new CreateConversationReq());
        String convId = resp.getConversation().getId();
        log.info("新会话已创建，conversationId={}", convId);
        return convId;
    }

    public Flowable<ChatEvent> streamChat(CreateChatReq req) {
        TokenAuth auth = new TokenAuth(cozeProperties.getPersonalToken());
        CozeAPI api = new CozeAPI.Builder()
                .baseURL(cozeProperties.getApiBase())
                .auth(auth)
                .readTimeout(60000)
                .build();
        return api.chat().stream(req);
    }

    public FileInfo uploadFile(String filePath) {
        TokenAuth auth = new TokenAuth(cozeProperties.getPersonalToken());
        CozeAPI api = new CozeAPI.Builder()
                .baseURL(cozeProperties.getApiBase())
                .auth(auth)
                .build();
        return api.files().upload(UploadFileReq.of(filePath))
                .getFileInfo();
    }
}
